package personal.dao.accounting;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import personal.domain.accounting.Account;
import personal.domain.accounting.AccountType;
import personal.domain.accounting.MonthendAccountBalance;
import personal.domain.accounting.MonthwiseCalendar;


@Repository
public class AccountDAOImpl implements AccountDAO {
	
	@PersistenceContext(unitName="accountingPU")
	private EntityManager em;
	private MonthwiseCalendarDAO monthwiseCalendarDAO;

	public MonthwiseCalendarDAO getMonthwiseCalendarDAO() {
		return monthwiseCalendarDAO;
	}

	@Autowired(required=false)
	public void setMonthwiseCalendarDAO(MonthwiseCalendarDAO monthwiseCalendarDAO) {
		this.monthwiseCalendarDAO = monthwiseCalendarDAO;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Account> getAllAccounts() {
		return em.createNamedQuery(Account.GET_ALL_ACCOUNTS).getResultList();
	}

	@Override
	public Account saveAccount(Account account) {
		return em.merge(account);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<AccountType> getAllAccountTypes() {
		return em.createNamedQuery(AccountType.GET_ALL_ACCOUNT_TYPES).getResultList();
	}

	@Override
	public AccountType saveAccountType(AccountType accountType) {
		return em.merge(accountType);
	}

	@Override
	public void saveMonthendAccountBalance(MonthendAccountBalance accountBalance) {
		em.merge(accountBalance);
	}

	@Override
	public int adjustMonthendAccountBalanceSince(MonthendAccountBalance accountBalance) {
		Query query = em.createNamedQuery(MonthendAccountBalance.UPDATE_MONTHEND_ACC_BAL_SINCE);
		query.setParameter("accountId", accountBalance.getAccountId());
		query.setParameter("calendarId", accountBalance.getCalendarId());
		query.setParameter("balDiff", accountBalance.getBalance());
		return query.executeUpdate();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MonthendAccountBalance> getCalendarMonthendAccountBalances(MonthwiseCalendar calendar) {
		List<Long> calendarIds = monthwiseCalendarDAO.getMonthwiseCalendarIds(monthwiseCalendarDAO.getMonthwiseCalendars(calendar));
		Query query = em.createNamedQuery(MonthendAccountBalance.GET_MONTHEND_ACC_BAL_FOR_CALENDARS);
		query.setParameter("calendarIdList", calendarIds);
		return query.getResultList();
	}
}
